package com.ultisense.gassensor;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

//java里面的Double和double是不一样的，double是基本变量属性，而Double是java打包好的一个class（具有多个属性）。
public class SourceFragment extends Fragment {

    Double a1, a2, a3, a4;
    Double x1, y1, l1, x, y;
    @BindView(R.id.source_map)
    ImageView sourceMap;
    @BindView(R.id.source_node1_blue)
    ImageView sourceNode1Blue;
    @BindView(R.id.source_node1_yellow)
    ImageView sourceNode1Yellow;
    @BindView(R.id.source_node1_red)
    ImageView sourceNode1Red;
    @BindView(R.id.source_node2_blue)
    ImageView sourceNode2Blue;
    @BindView(R.id.source_node2_yellow)
    ImageView sourceNode2Yellow;
    @BindView(R.id.source_node2_red)
    ImageView sourceNode2Red;
    @BindView(R.id.source_node3_blue)
    ImageView sourceNode3Blue;
    @BindView(R.id.source_node3_yellow)
    ImageView sourceNode3Yellow;
    @BindView(R.id.source_node3_red)
    ImageView sourceNode3Red;
    @BindView(R.id.source_node4_blue)
    ImageView sourceNode4Blue;
    @BindView(R.id.source_node4_yellow)
    ImageView sourceNode4Yellow;
    @BindView(R.id.source_node4_red)
    ImageView sourceNode4Red;

    int nodeStatus = 1;
    double baseline = 0;
    double baseline_1;
    double baseline_2;
    double baseline_3;
    double baseline_4;
    private static float[] saveData_1 = new float[10];
    private static float[] saveData_2 = new float[10];
    private static float[] saveData_3 = new float[10];
    private static float[] saveData_4 = new float[10];
    private static int dataAvrCount_1 = 0;
    private static int dataAvrCount_2 = 0;
    private static int dataAvrCount_3 = 0;
    private static int dataAvrCount_4 = 0;

    /**
     * SourceCalculation代表一个class，
     * SourceCalculation是这个class的名字，不可以直接调用,必须要定义一个新变量，这个新变量属于这个class。然后调用这个变量，
     * 这个变量就继承了SourceCalculation的全部属性，至于new SourceCalculation()是格式规范，表示新定义的这个sourceData属于SourceCalculation。
     * 这个class可以public，也可以private，和C的结构体很像。
     */
    SourceCalculation sourceData = new SourceCalculation();

    //get node num of H2
    int sensorNum_1 = 1;
    int sensorNum_2 = 2;
    int sensorNum_3 = 3;
    int sensorNum_4 = 4;
    int sensorNum = 1;
    @BindView(R.id.source_location)
    ImageView sourceLocation;
    @BindView(R.id.source_start)
    TextView sourceStart;
    @BindView(R.id.source_auto)
    TextView sourceAuto;
    @BindView(R.id.source_status)
    TextView sourceStatus;
    @BindView(R.id.source_node1_con)
    TextView sourceNode1Con;
    @BindView(R.id.source_node1)
    LinearLayout sourceNode1;
    @BindView(R.id.source_node2_con)
    TextView sourceNode2Con;
    @BindView(R.id.source_node2)
    LinearLayout sourceNode2;
    @BindView(R.id.source_node3_con)
    TextView sourceNode3Con;
    @BindView(R.id.source_node3)
    LinearLayout sourceNode3;
    @BindView(R.id.source_node4_con)
    TextView sourceNode4Con;
    @BindView(R.id.source_node4)
    LinearLayout sourceNode4;


    public SourceFragment() {
        // Required empty public constructor
    }

    public static SourceFragment newInstance() {
        SourceFragment fragment = new SourceFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        mHandler = new Handler();
        mData = new DataProcessor();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_source, container, false);
        ButterKnife.bind(this, v);
        createView(v);
        return v;
    }


    private void createView(View v) {
        sourceMap = v.findViewById(R.id.source_map);
        sourceNode1Blue = v.findViewById(R.id.source_node1_blue);
        sourceNode1Yellow = v.findViewById(R.id.source_node1_yellow);
        sourceNode1Red = v.findViewById(R.id.source_node1_red);
        sourceNode2Blue = v.findViewById(R.id.source_node2_blue);
        sourceNode2Yellow = v.findViewById(R.id.source_node2_yellow);
        sourceNode2Red = v.findViewById(R.id.source_node2_red);
        sourceNode3Blue = v.findViewById(R.id.source_node3_blue);
        sourceNode3Yellow = v.findViewById(R.id.source_node3_yellow);
        sourceNode3Red = v.findViewById(R.id.source_node3_red);
        sourceNode4Blue = v.findViewById(R.id.source_node4_blue);
        sourceNode4Yellow = v.findViewById(R.id.source_node4_yellow);
        sourceNode4Red = v.findViewById(R.id.source_node4_red);

        sourceStart = v.findViewById(R.id.source_start);
        sourceLocation = v.findViewById(R.id.source_location);
        sourceAuto = v.findViewById(R.id.source_auto);
        sourceStatus = v.findViewById(R.id.source_status);

        sourceNode1Con=v.findViewById(R.id.source_node1_con);
        sourceNode2Con=v.findViewById(R.id.source_node2_con);
        sourceNode3Con=v.findViewById(R.id.source_node3_con);
        sourceNode4Con=v.findViewById(R.id.source_node4_con);

        sourceStart.setOnClickListener(new View.OnClickListener() {//one time
            @Override
            public void onClick(View v) {
                singleRoundCount = 0;
                setGetAxis();
                getDataNew();
//                singleRotate();
            }
        });

        sourceAuto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setGetAxis();
            }
        });

    }

    static ArrayList<String> dataList1=new ArrayList<String>();
    static ArrayList<String> dataList2=new ArrayList<String>();
    static ArrayList<String> dataList3=new ArrayList<String>();
    static ArrayList<String> dataList4=new ArrayList<String>();
    int dataListLength;
    int readingPlace=0;
    //200515
    public void getDataNew(){
        ReadTxtFile(dataList1,"/data/data/com.ultisense.gassensor/data/sensor1.txt");
        ReadTxtFile(dataList2,"/data/data/com.ultisense.gassensor/data/sensor2.txt");
        ReadTxtFile(dataList3,"/data/data/com.ultisense.gassensor/data/sensor3.txt");
        ReadTxtFile(dataList4,"/data/data/com.ultisense.gassensor/data/sensor4.txt");
        dataListLength=dataList1.size();
    }
    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            String data1=dataList1.get(readingPlace);
            String data2=dataList2.get(readingPlace);
            String data3=dataList3.get(readingPlace);
            String data4=dataList4.get(readingPlace);
            readingPlace=readingPlace+1;

            sourceNode1Con.setText(data1+" ppm");
            sourceNode2Con.setText(data2+" ppm");
            sourceNode3Con.setText(data3+" ppm");
            sourceNode4Con.setText(data4+" ppm");

            handler.postDelayed(this,1000);
        }
    };
    public static Double String2Double(String stringData){
        Double result=new Double(stringData);
        return result;
    }

    public static String ReadTxtFile(ArrayList dataList,String strFilePath)
    {
        String path = strFilePath;
        //打开文件
        File file;
        file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory())
        {
            Log.e("TestFile", "The File doesn't not exist.");
        }
        else
        {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null)
                {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while (( line = buffreader.readLine()) != null) {
                        dataList.add(line+"\n");
                    }
                    instream.close();
                }
            }
            catch (java.io.FileNotFoundException e)
            {
                Log.e("TestFile", "The File doesn't not exist.");
            }
            catch (IOException e)
            {
                Log.e("TestFile", e.getMessage());
            }
        }
        return strFilePath;
    }

    public void setGetAxis() {
        int[] location1 = new int[2];
        int[] location2 = new int[2];
        int[] location3 = new int[2];
        int[] location4 = new int[2];
        sourceNode1Blue.getLocationInWindow(location1);
        sourceNode2Blue.getLocationInWindow(location2);
        sourceNode3Blue.getLocationInWindow(location3);
        sourceNode4Blue.getLocationInWindow(location4);
        sourceData.setAxis(location1, location2, location3, location4);
    }


    private void autoRotate() {
        findBT();
    }

    int singleRoundCount;
    int ProcessType;//1 Single 2 Auto 3 Setbase

    public void singleRotate() {
        ProcessType = 1;
        if (singleRoundCount < 4) {
            findBT();
        } else {
            ProcessType = 4;
            try {
                closeBT();
            } catch (IOException e) {
            }
            sourceData.calculation();
            int position_x = sourceData.getX_position();
            int position_y = sourceData.getY_position();
            drawSourcePoint(position_x, position_y);
        }
        singleRoundCount = singleRoundCount + 1;
    }

    /*****tool function******/
    private DataProcessor mData;
    private static BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private Handler mHandler;
    private BluetoothDevice mmDevice;
    private static BluetoothGatt mBluetoothGatt;
    BluetoothGattCharacteristic mCharacteristic;
    BluetoothGattDescriptor mDescriptor;
    private Thread workerThread;

    private boolean findDevice;

    public void findBT() {
        mBluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.i("bt", "No bluetooth adapter available");
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }
        startScan();
    }

    private void startScan() {
        mHandler.postDelayed(stopScanRunnable, 2000);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }

    /**
     * address of different nodes
     * set different nodes by changing the flag status value
     **/
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             byte[] scanRecord) {
            getActivity().runOnUiThread(new Runnable() {

                public void run() {


                    //change address by status
                    switch (nodeStatus) {
                        case 1:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A1")) {
                                    findDevice = true;
                                    sensorNum = sensorNum_1;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 2:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A2")) {
                                    findDevice = true;
                                    sensorNum = sensorNum_2;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 3:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A3")) {
                                    findDevice = true;
                                    sensorNum = sensorNum_3;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                        case 4:
                            if (device.getName() != null) {
                                //myRecord.append(toHex(device.getName())+"\n");
                                if (device.getName().equals("A4")) {
                                    findDevice = true;
                                    sensorNum = sensorNum_4;
                                    mmDevice = device;
                                    try {
                                        openBT();
                                    } catch (IOException ex) {
                                    }
                                }
                            }
                            break;
                    }
                }
            });
        }
    };

    private Runnable stopScanRunnable = new Runnable() {
        @Override
        public void run() {
            if (mBluetoothAdapter != null) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
            if (mmDevice == null) {
                Log.i("bt", "No matching device found! Try again!");
            }
        }
    };

    public void openBT() throws IOException {
        if (mmDevice != null) {
            //修改BLE接口最大接收大小 190918 LMT
            mBluetoothGatt = mmDevice.connectGatt(getContext(), false, mGattCallback);
        } else {
            Log.i("bt", "Please connect to device first!");
        }

    }

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (mBluetoothGatt != null) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    //改变mtu大小
                    if (Build.VERSION.SDK_INT > 20) {
                        boolean ret = gatt.requestMtu(512);
                        Log.d("BLE", "requestMTU " + 512 + " ret=" + ret);
                    }

                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    try {
                        closeBT();
                    } catch (IOException e) {
                    }
                }
            } else {
                Log.e("data", "discover when null");
                try {
                    closeBT();
                } catch (IOException e) {
                    Log.e("discover", e.getMessage());
                }
//                findBT();
            }
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            Log.d("onMtuChanged", " onMtuChanged");
            if (BluetoothGatt.GATT_SUCCESS == status) {
                Log.d("BleService", "onMtuChanged success MTU = " + mtu);
                mBluetoothGatt.discoverServices();
                /*final Intent intent = new Intent("com.example.bluetooth.le.ACTION_GATT_CONNECTED");
                getActivity().sendBroadcast(intent);*/
                Log.i("onConnection: ", "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i("onConnection: ", "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());
            } else {
                Log.d("BleService", "onMtuChanged fail ");
            }
        }


        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                mCharacteristic = mBluetoothGatt.getService(UUID.fromString("0003cdd0-0000-1000-8000-00805f9b0131")).getCharacteristic(UUID.fromString("0003cdd1-0000-1000-8000-00805f9b0131"));
                Log.i("onServicesDiscovered: ", "found characteristic!");
                mBluetoothGatt.setCharacteristicNotification(mCharacteristic, true);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        myLabel.setText("Bluetooth Opened!");
//                        myCheckbox.setChecked(true);
                    }
                });
                if (mCharacteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")) != null) {
                    mDescriptor = mCharacteristic
                            .getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                    mDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(mDescriptor);
                    Log.i("onServicesDiscovered: ", "enabled notification!");
                }

            } else {
                Log.i("onServicesDiscovered: ", Integer.toString(status));
            }
        }

        public void getBaseline(DataProcessor data) {
            if (baseline_1 == 0) {
                saveData_1 = new float[10];
                dataAvrCount_1 = 0;
                baseline_1 = dataAverage(data.getSingleData(sensorNum_1), saveData_1, dataAvrCount_1) + 2f;
            }
            if (baseline_2 == 0) {
                saveData_2 = new float[10];
                dataAvrCount_2 = 0;
                baseline_2 = dataAverage(data.getSingleData(sensorNum_2), saveData_2, dataAvrCount_2) + 2f;
            }
            if (baseline_3 == 0) {
                saveData_3 = new float[10];
                dataAvrCount_3 = 0;
                baseline_3 = dataAverage(data.getSingleData(sensorNum_3), saveData_3, dataAvrCount_3) + 2f;
            }
            if (baseline_4 == 0) {
                saveData_4 = new float[10];
                dataAvrCount_4 = 0;
                baseline_4 = dataAverage(data.getSingleData(sensorNum_4), saveData_4, dataAvrCount_4) + 2f;
            }
        }

        //get data
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            //data processing
            long appTime = System.currentTimeMillis();
            final byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                nodeStatus = data[1];
                mData.storeData(data);
                long sensorTime = mData.getSensorTime(data);
                if (nodeStatus < 5) {
                    if (sourceData.syncSensorTime[nodeStatus - 1] == null) {
                        sourceData.syncTime(nodeStatus, sensorTime, appTime);
                    }
                } else {
                    int nodeTrueStatus = nodeStatus - 4;
                    if (sourceData.flagTime[nodeTrueStatus - 1] == null) {
                        sourceData.getFlagTime(sensorTime, nodeTrueStatus);
                    }
                }

                /**baseline*/
                getBaseline(mData);
//                baseline=0;
//                getData();
            }
        }
    };


    public void drawSourcePoint(int x, int y) {
        sourceLocation.setX(x);
        sourceLocation.setY(y);
        sourceLocation.setVisibility(View.VISIBLE);
    }

    public void closeBT() throws IOException {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        Log.i("data", "stop" + nodeStatus);
        mBluetoothGatt = null;
        switch (ProcessType) {
            case 1://single
                singleRotate();
                break;
            case 2://auto
                autoRotate();
                break;
            case 3://set
                break;
            case 4://stop everything
                break;
        }

    }

    /**
     * Data Process
     */
//data average
//set the default value of node
    public static float nodeDefault = 0;

    public static float dataAverage(float data, float[] saveData, int dataAvrCount) {
        float sumData = 0;
        //adapt savedata
        if (dataAvrCount < 10) {
            saveData[dataAvrCount] = data;
        } else {
            for (int j = 0; j < 9; j++) {
                saveData[j] = saveData[j + 1];
            }
            saveData[9] = data;
        }
        //calculate average
        for (int k = 0; k < 10; k++) {
            sumData = sumData + saveData[k];
        }
        int avaCount = 1;
        if (dataAvrCount < 10) {
            avaCount = dataAvrCount + 1;
            //take the average of first 10 points as the default value of node
            nodeDefault = sumData / avaCount;
        } else {
            avaCount = 10;
        }
        float avaNum = sumData / avaCount;
        dataAvrCount++;
        return avaNum;
    }


//    public void getData() {
//        getActivity().runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                double value_1 = 0.0;
//                double value_2 = 0.0;
//                double value_3 = 0.0;
//                double value_4 = 0.0;
//                double sen_1 = 0.0;
//                double con_1 = 0.0;
//                double sen_2 = 0.0;
//                double con_2 = 0.0;
//                double sen_3 = 0.0;
//                double con_3 = 0.0;
//                double sen_4 = 0.0;
//                double con_4 = 0.0;
//
//                int h2_warn = 100;
//                int h2_alarm = 2000;
//
//
//                switch (nodeStatus) {
//                    case 1:
//                        value_1 = DataProcessor.getSingleData(sensorNum_1);
//                        sen_1 = DataProcessor.sensitivity(baseline_1, value_1);
////                        if (sen_1 < 0.03) {
////                            sourceText1Result.setText("No leakage detected");
////                        } else {
//                        con_1 = DataProcessor.concentration(sen_1, 1);
//                        Integer see_1 = (int) con_1;
//                        sourceText1Result.setText(see_1.toString() + " ppm");
//                        if (con_1 > h2_alarm) {
//                            sourceText1Result.setTextColor(getResources().getColor(R.color.red));
//                            sourceNode1Red.setVisibility(View.VISIBLE);
//                            sourceNode1Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode1Blue.setVisibility(View.INVISIBLE);
//                        } else if (con_1 > h2_warn) {
//                            sourceText1Result.setTextColor(getResources().getColor(R.color.yellow));
//                            sourceNode1Red.setVisibility(View.INVISIBLE);
//                            sourceNode1Yellow.setVisibility(View.VISIBLE);
//                            sourceNode1Blue.setVisibility(View.INVISIBLE);
//                        } else {
//                            sourceText1Result.setTextColor(getResources().getColor(R.color.deep_green));
//                            sourceNode1Red.setVisibility(View.INVISIBLE);
//                            sourceNode1Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode1Blue.setVisibility(View.VISIBLE);
//                        }
////                        }
//                        break;
//                    case 2:
//                        value_2 = DataProcessor.getSingleData(sensorNum_2);
//                        sen_2 = DataProcessor.sensitivity(baseline_2, value_2);
////                        if (sen_2 < 0.03) {
////                            sourceText2Result.setText("No leakage detected");
////                        } else {
//                        con_2 = DataProcessor.concentration(sen_2, 1);
//                        Integer see_2 = (int) con_2;
//                        sourceText2Result.setText(see_2.toString() + " ppm");
//                        if (con_2 > h2_alarm) {
//                            sourceText2Result.setTextColor(getResources().getColor(R.color.red));
//                            sourceNode2Red.setVisibility(View.VISIBLE);
//                            sourceNode2Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode2Blue.setVisibility(View.INVISIBLE);
//                        } else if (con_2 > h2_warn) {
//                            sourceText2Result.setTextColor(getResources().getColor(R.color.yellow));
//                            sourceNode2Red.setVisibility(View.INVISIBLE);
//                            sourceNode2Yellow.setVisibility(View.VISIBLE);
//                            sourceNode2Blue.setVisibility(View.INVISIBLE);
//                        } else {
//                            sourceText2Result.setTextColor(getResources().getColor(R.color.deep_green));
//                            sourceNode2Red.setVisibility(View.INVISIBLE);
//                            sourceNode2Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode2Blue.setVisibility(View.VISIBLE);
//                        }
////                        }
//                        break;
//                    case 3:
//                        value_3 = DataProcessor.getSingleData(sensorNum_3);
//                        sen_3 = DataProcessor.sensitivity(baseline_3, value_3);
////                        if (sen_3 < 0.03) {
////                            sourceText3Result.setText("No leakage detected");
////                        } else {
//                        con_3 = DataProcessor.concentration(sen_3, 1);
//                        Integer see_3 = (int) con_3;
//                        sourceText3Result.setText(see_3.toString() + " ppm");
//                        if (con_3 > h2_alarm) {
//                            sourceText3Result.setTextColor(getResources().getColor(R.color.red));
//                            sourceNode3Red.setVisibility(View.VISIBLE);
//                            sourceNode3Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode3Blue.setVisibility(View.INVISIBLE);
//                        } else if (con_3 > h2_warn) {
//                            sourceText3Result.setTextColor(getResources().getColor(R.color.yellow));
//                            sourceNode3Red.setVisibility(View.INVISIBLE);
//                            sourceNode3Yellow.setVisibility(View.VISIBLE);
//                            sourceNode3Blue.setVisibility(View.INVISIBLE);
//                        } else {
//                            sourceText3Result.setTextColor(getResources().getColor(R.color.deep_green));
//                            sourceNode3Red.setVisibility(View.INVISIBLE);
//                            sourceNode3Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode3Blue.setVisibility(View.VISIBLE);
//                        }
////                        }
//                        break;
//                    case 4:
//                        value_4 = DataProcessor.getSingleData(sensorNum_4);
//                        sen_4 = DataProcessor.sensitivity(baseline_4, value_4);
////                        if (sen_4 < 0.03) {
////                            sourceText4Result.setText("No leakage detected");
////                        } else {
//                        con_4 = DataProcessor.concentration(sen_4, 1);
//                        Integer see_4 = (int) con_4;
//                        sourceText4Result.setText(see_4.toString() + " ppm");
//                        if (con_4 > h2_alarm) {
//                            sourceText4Result.setTextColor(getResources().getColor(R.color.red));
//                            sourceNode4Red.setVisibility(View.VISIBLE);
//                            sourceNode4Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode4Blue.setVisibility(View.INVISIBLE);
//                        } else if (con_4 > h2_warn) {
//                            sourceText4Result.setTextColor(getResources().getColor(R.color.yellow));
//                            sourceNode4Red.setVisibility(View.INVISIBLE);
//                            sourceNode4Yellow.setVisibility(View.VISIBLE);
//                            sourceNode4Blue.setVisibility(View.INVISIBLE);
//                        } else {
//                            sourceText4Result.setTextColor(getResources().getColor(R.color.deep_green));
//                            sourceNode4Red.setVisibility(View.INVISIBLE);
//                            sourceNode4Yellow.setVisibility(View.INVISIBLE);
//                            sourceNode4Blue.setVisibility(View.VISIBLE);
//                        }
////                        }
//                        break;
//                }
//                if (nodeStatus == 4) {//条件未决定
//                    sourceStatus.setText("LEAKAGE DETECTED");
//                    sourceStatus.setTextColor(getResources().getColor(R.color.red));
//                }
//                nodeStatus = nodeStatus % 4 + 1;
//                try {
//                    closeBT();
//                } catch (IOException e) {
//                }
//            }
//        });
//
//    }

    @Override
    public void onStop() {
        try {
            closeBT();
        } catch (IOException e) {
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
